var role = require("../lib/role");
var BlogCon = iClass("Blog");
module.exports = {
	prefix: "/blog",
	get: {
		"/list": function() {
			var query = this.request.query;
			try {
				//尝试获取登录用户
				var user = role.getUser(this);
			} catch (e) {}
			var blog_list_info = BlogCon.getOpenList(user, query.type, query.key, query.num, query.page);
			this.body = ResponObj("json", blog_list_info);
		},
		"/by_id/:blog_id": function() {
			var blog_id = this.params.blog_id;
			var blog = BlogCon.get(blog_id);
			if (!blog) {
				Throw("找不到指定博文" + blog_id)
			}
			try {
				//尝试获取登录用户
				var user = role.getUser(this);
			} catch (e) {}
			//query对象中可能存在钥匙信息
			var blog_key = this.request.query.key;
			if (!blog.isOpenForSomeUser(user && user._id, blog_key)) {
				Throw("没有浏览这篇博文的权限")
			}
			this.body = ResponObj("json", blog.getDetail(user && user._id));
		},
		"/list_by_tag_id/:tag_id": function() {
			var tag_id = this.params.tag_id;
			var query = this.request.query;
			try {
				//尝试获取登录用户
				var user = role.getUser(this);
			} catch (e) {}
			var blog_list_info = BlogCon.getOpenListByTag(tag_id, user, query.type, query.key, query.num, query.page);
			this.body = ResponObj("json", blog_list_info);
		},
		"/hot_comments/by_id/:blog_id": function() {
			var blog_id = this.params.blog_id;
			var blog = BlogCon.get(blog_id);
			if (!blog) {
				Throw("找不到指定博文" + blog_id)
			}
			try {
				//尝试获取登录用户
				var user = role.getUser(this);
			} catch (e) {}
			//query对象中可能存在钥匙信息
			var blog_key = this.request.query.key;
			if (!blog.isOpenForSomeUser(user && user._id, blog_key)) {
				Throw("没有浏览这篇博文的权限")
			}
			this.body = ResponObj("json", blog.getHostComments(user && user._id));
		}
	},
	post: {
		"/add_comment/:blog_id": function() {
			var user = role.getUser(this);
			//校验用户与博文的权限
			var blog_id = this.params.blog_id;
			var blog = BlogCon.get(blog_id);
			if (!blog) {
				Throw("找不到指定博文" + blog_id)
			}
			var blog_key = this.request.query.key;
			if (!blog.isOpenForSomeUser(user._id, blog_key)) {
				Throw("没有浏览这篇博文的权限")
			}

			//添加评论
			var comment_info = this.request.body;
			var comment = user.addCommentToBlog(blog_id, comment_info);

			this.body = ResponObj("json", comment);
		}
	}
}